﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Text;
using LogManager.Base;
using LogManager.Base.Data;
using LogManager.Base;

namespace LogManager.Windows.Data
{
    /// <summary>
    /// This is a event service that can be used in a specific log access method    
    /// </summary>
    public class WindowsEventExportService : IEventExportService
    {
        private IEventTypeService _typeService;

        public WindowsEventExportService(string serverName, string logName, IEventTypeService typeService)
        {            
            LogName = logName;
            ServerName = serverName;
            _typeService = typeService;
        }

        //Reader
        /// <summary>
        /// Return a list of events of a log. todo: Workaround, it's suboptimal to have the whole list in RAM.
        /// </summary>
        /// <param name="log">The log that contains the events</param>
        /// <param name="queryText">The query text for the log</param>
        /// <returns></returns>
        private IEnumerable<IEvent> ReadEvents(string serverName,string logName, string queryText = "*")
        {
            //Init session
            var query = new EventLogQuery(logName, PathType.LogName, queryText)
            {
                Session = new EventLogSession()
            };

            //Excecute reader
            using (var reader = new EventLogReader(query))
            {
                EventRecord record;

                //Return mapped event
                while ((record = reader.ReadEvent()) != null)
                {
                    IEvent @event = new Event();
                    @event.Initialize(serverName, logName);
                    yield return WindowsEventMapper.MapEvent(@event, record);
                }
            }
        }

        #region Implementation of IDisposable

        public void Dispose()
        {
            //Do nothing
        }

        #endregion

        #region Implementation of IEventExportService

        public string LogName { get; set; }

        public string ServerName { get; set; }

        public IEnumerable<IEvent> Export(DateTime start, DateTime end)
        {
            var builder = new WindowsEventQueryBuilder();
            
            //string query = builder.Where(WindowsEventQueryBuilder.TimeRangeCondition(start, end)).CreateQuery();

            //note: very resource intensive
            return ReadEvents(ServerName, LogName).AsParallel().Where(e => e.TimeStamp > start && e.TimeStamp < end);
        }

        #endregion
    }
}
